<?php
/**
 * @Copyright: (C)2021 BJYHYY Inc. All Rights Reserved.
 * @Author: xuzy
 * @Date: 2021/2/24 19:59
 */

namespace App\Console\Commands;

use App\Model\Files;
use Illuminate\Console\Command;

class UpdateImg extends Command
{
    /**
     * 命令行执行命令
     * @var string
     */
    protected $signature = 'update_img';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '将亚马逊图片切换到本地';

    /**
     * Create a new command instance.
     *可以去掉不影响使用
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $list = Files::where('set_uri','like','%https://umijoy.s3.cn-north-1.amazonaws.com.cn%')->get();
        $count = 0;
        foreach ($list as $key=>$value){
            $saveDir = realpath('./public/img/');
            if(!is_dir($saveDir)){
                mkdir($saveDir,0777,true);
            }
            $filename = date('YmdHis').rand(0,1000).'.png';
            $savePath = $saveDir.'/'.$filename;
            $file_url = $value['set_uri'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch,CURLOPT_URL,$file_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $file_content = curl_exec($ch);
            curl_close($ch);
            $downloaded_file = fopen($savePath, 'w');
            fwrite($downloaded_file, $file_content);
            fclose($downloaded_file);
            $url = 'http://file.api.umijoy.com/img/'.$filename;
            $value->set_uri = $url;
            $value->save();
            $count+=1;
        }
        return 'success:'.$count;
    }
}